package com.allwees.bs.c.common.auth.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allwees.bs.core.modelbase.constant.ErrorMessage;
import com.allwees.bs.core.modelbase.constant.ResultCode;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于发送http请求
 *
 * @author jy2016
 *
 */
public class HttpUtil {
	protected static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	private static CloseableHttpClient client;

	private static CloseableHttpResponse response;

	static {
//		HttpHost proxy = new HttpHost("localhost",1080);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).build();
//		client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
		client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
	}

	private HttpUtil() {
	}


	private static final Header HEADER_USER_AGENT = new BasicHeader("User-Agent",
			"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");

	public static JSONObject get(String url) {
		HttpGet getMethod = new HttpGet(url);
		getMethod.addHeader(HEADER_USER_AGENT);
		try {
			response = client.execute(getMethod);
			HttpEntity repEntity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode != HttpStatus.SC_OK) {
				getMethod.abort();
				String content = EntityUtils.toString(repEntity, "UTF-8");
				JSONObject json = JSON.parseObject(content);
				logger.error(json.toJSONString());
				throw BusinessException.getInstance(ResultEnum.THIRD_PARTY_STATUS_ERROR, new Object[]{statusCode, url});
			} else {
				String content = EntityUtils.toString(repEntity, "UTF-8");
				JSONObject json = JSON.parseObject(content);
				return json;
			}

		} catch(Exception e) {
			logger.error("get exception", e);
			throw BusinessException.getInstance(ResultEnum.THIRD_PARTY_ERROR, new Object[]{url});
		} finally {
			if(response != null) {
				try {
					response.close();
				} catch(Exception e) {
				}
			}
		}
	}
}
